<?php
/**
 * 
 * News module
 * 
 * @name			News
 * @description		Standard news module for Cosa admin
 * @version			1.0.0
 * 
 * @author			Stijn Van Minnebruggen
 * @author_url		www.donotfold.be
 * @module_url		www.donotfold.be/projects/cosa
 * 
 * @sub1			news
 * @sub2			cat
 * 
 */

class news extends Module
{
	
	/**
	 * Install script for module
	 * 
	 * @return	bool
	 */
	
	public function install()
	{
		// required
			global $cosa, $db, $user;
		
		// create main table
			$sql = "CREATE TABLE IF NOT EXISTS `".$db->module('news')."` (
					`id` int(11) NOT NULL auto_increment,
					`language_id` int(11) NOT NULL,
					`title` varchar(255) NOT NULL,
					`text` text,
					`created_by` int(11) NOT NULL,
					`time_created` datetime NOT NULL,
					`time_modified` datetime NOT NULL,
					PRIMARY KEY  (`id`)
					) ENGINE=MyISAM;
					";
			if(!@mysql_query($sql)) return 'Could not install news module (1).';
		
		// create second table
			$sql = "CREATE TABLE IF NOT EXISTS `".$db->module('news_cat')."` (
					`id` int(11) NOT NULL auto_increment,
					`language_id` int(11) NOT NULL,
					`title` varchar(255) NOT NULL,
					`default` enum('1','0') NOT NULL default '0',
					`created_by` int(11) NOT NULL,
					`time_created` datetime NOT NULL,
					`time_modified` datetime NOT NULL,
					PRIMARY KEY  (`id`)
					) ENGINE=MyISAM;
					";
			if(!@mysql_query($sql)) return 'Could not install news module (2).';
		
		// create third table
			$sql = "CREATE TABLE IF NOT EXISTS `".$db->module('news_rel')."` (
					`news_id` int(11) NOT NULL,
					`cat_id` int(11) NOT NULL,
					PRIMARY KEY  (`news_id`,`cat_id`)
					) ENGINE=MyISAM;
					";
			if(!@mysql_query($sql)) return 'Could not install news module (3).';
		
		// return success
			return true;
		
	}
	
	
	/**
	 * Uninstall script for module
	 * 
	 * @return	bool
	 */
	
	public function uninstall()
	{
		global $cosa;
		$sql = "DROP TABLE `".$db->module('news')."`";
		@mysql_query($sql) or $cosa->oops('Could not uninstall news module (1).', 'db');
		$sql = "DROP TABLE `".$db->module('news_cat')."`";
		@mysql_query($sql) or $cosa->oops('Could not uninstall news module (2).', 'db');
		$sql = "DROP TABLE `".$db->module('news_rel')."`";
		@mysql_query($sql) or $cosa->oops('Could not uninstall news module (3).', 'db');
		return true;
	}
	
	
	/**
	 * Add a news item
	 * 
	 * @param	array	$postVars
	 * @return	bool
	 */
	
	public function news_add($postVars)
	{
		// required
			global $cosa, $db, $user, $modules, $lang, $path;
			if(!isset($postVars) || empty($postVars)) {
				$modules->addMessage($lang->get('add-news-failed'));
				return false;
			}
		
		// add news
			$sql = "INSERT INTO ".$db->module('news')."
					SET	language_id		= '".$lang->id."'
						,title			= '".addslashes($postVars['title'])."'
						,text			= '".addslashes($postVars['text'])."'
						,created_by		= '".addslashes($user->id())."'
						,time_created	= NOW()
						,time_modified	= NOW()
					";
			@mysql_query($sql) or $cosa->kill($lang->get('add-news-failed'), 'db');
			$news_id = mysql_insert_id();
		
		// save path data
			$path->create($postVars['title'], $db->module('news'), $lang->id, $news_id);
		
		// update categories
			$this->_updateCategories($news_id, $postVars);
		
		// return success
			$modules->addMessage($lang->get('add-news-success'));
			return true;
		
	}
	
	
	/**
	 * Edit a news item
	 * 
	 * @param	array	$postVars
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function news_edit($postVars, $id)
	{
		// required
			global $cosa, $db, $user, $modules, $lang, $path;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('edit-news-failed'));
				return false;
			}
		
		// edit page
			$sql = "UPDATE ".$db->module('news')."
					SET	title			= '".addslashes($postVars['title'])."'
						,text			= '".addslashes($postVars['text'])."'
						,created_by		= '".addslashes($user->id())."'
						,time_modified	= NOW()
					WHERE
						id				= '".addslashes($postVars['edit'])."'
					";
			@mysql_query($sql) or $cosa->kill($lang->get('edit-news-failed'), 'db');
		
		// save path data
			$path->create($postVars['title'], $db->module('news'), $lang->id, $postVars['edit']);
		
		// update categories
			$this->_updateCategories($postVars['edit'], $postVars);
		
		// return success
			$modules->addMessage($lang->get('edit-news-success'));
			return true;
		
	}
	
	
	/**
	 * Delete a news item
	 * 
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function news_del($id)
	{
		// required
			global $cosa, $db, $modules, $lang, $path;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('del-news-failed'));
				return false;
			}
		
		// execute query 1
			$sql = "DELETE FROM ".$db->module('news')." WHERE id ='".addslashes($id)."' LIMIT 1";
			@mysql_query($sql) or $cosa->kill($lang->get('del-news-failed'), 'db');
		
		// delete path
			$path->delete($db->module('news'), $id);
		
		// update categories
			$this->_updateCategories($id, array());
		
		// add message to pool
			$modules->addMessage($lang->get('del-news-success'));
			return true;
		
	}
	
	
	/**
	 * Get one news item
	 * 
	 * @param	int		$id
	 * @return	array
	 */
	
	public function news_get($id)
	{
		// required
			global $cosa, $db;
			if(!isset($id) || empty($id)) return false;
		
		// execute query
			$sql = "SELECT * FROM ".$db->module('news')." WHERE id ='".addslashes($id)."' LIMIT 1";
			$res = @mysql_query($sql) or $cosa->oops('Could not fetch item.', 'db');
		
		// return result
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Add a news category
	 * 
	 * @param	array	$postVars
	 * @return	bool
	 */
	
	public function cat_add($postVars)
	{
		// required
			global $cosa, $db, $user, $modules, $lang;
			if(!isset($postVars) || empty($postVars)) {
				$modules->addMessage($lang->get('add-news-cat-failed'));
				return false;
			}
		
		// check given default
			$default = (isset($postVars['default']) && $postVars['default']) ? 1 : 0;
			if($default) {
				$sql = "UPDATE ".$db->module('news_cat')." SET `default` = '0'";
				@mysql_query($sql) or $cosa->kill($lang->get('add-news-cat-failed'), 'db');
			}
		
		// check if other default is set
			$otherDefault = $this->getDefaultCat();
			if(!$otherDefault) $default = 1;
		
		// add news
			$sql = "INSERT INTO ".$db->module('news_cat')."
					SET	language_id		= '".$lang->id."'
						,title			= '".addslashes($postVars['title'])."'
						,`default`		= '".$default."'
						,created_by		= '".addslashes($user->id())."'
						,time_created	= NOW()
						,time_modified	= NOW()
					";
			@mysql_query($sql) or $cosa->kill($lang->get('add-news-cat-failed'), 'db');
		
		// return success
			$modules->addMessage($lang->get('add-news-cat-success'));
			return true;
		
	}
	
	
	/**
	 * Edit a news category
	 * 
	 * @param	array	$postVars
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function cat_edit($postVars, $id)
	{
		// required
			global $cosa, $db, $user, $modules, $lang;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('edit-news-cat-failed'));
				return false;
			}
		
		// check given default
			$default = ($postVars['default']) ? 1 : 0;
			if($default) {
				$sql = "UPDATE ".$db->module('news_cat')." SET `default` = '0'";
				@mysql_query($sql) or $cosa->kill($lang->get('add-news-cat-failed'), 'db');
			}
		
		// check if other default is set
			$otherDefault = $this->getDefaultCat();
			if(!$otherDefault) $default = 1;
		
		// edit page
			$sql = "UPDATE ".$db->module('news_cat')."
					SET	title			= '".addslashes($postVars['title'])."'
						,`default`		= '".$default."'
						,created_by		= '".addslashes($user->id())."'
						,time_modified	= NOW()
					WHERE
						id				= '".addslashes($postVars['edit'])."'
					";
			@mysql_query($sql) or $cosa->kill($lang->get('edit-news-cat-failed'), 'db');
		
		// return success
			$modules->addMessage($lang->get('edit-news-cat-success'));
			return true;
		
	}
	
	
	/**
	 * Delete a news category
	 * 
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function cat_del($id)
	{
		// required
			global $cosa, $db, $modules, $lang;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('del-news-cat-failed'));
				return false;
			}
		
		// check for default
			$sql = "SELECT `default` FROM ".$db->module('news_cat')." WHERE id='".addslashes($id)."' LIMIT 1";
			$res = @mysql_query($sql) or $cosa->kill($lang->get('del-news-cat-failed'), 'db');
			$row = mysql_fetch_array($res);
			$wasDefault = ($row['default']) ? 1 : 0;
		
		// execute query
			$sql = "DELETE FROM ".$db->module('news_cat')." WHERE id ='".addslashes($id)."' LIMIT 1";
			@mysql_query($sql) or $cosa->kill($lang->get('del-news-cat-failed'), 'db');
		
		// set other default
			if($wasDefault) {
				$sql = "UPDATE ".$db->module('news_cat')." SET `default` = '1' LIMIT 1";
				@mysql_query($sql) or $cosa->kill($lang->get('del-news-cat-failed'), 'db');
			}
		
		// add message to pool
			$modules->addMessage($lang->get('del-news-cat-success'));
			return true;
		
	}
	
	
	/**
	 * Get one news category
	 * 
	 * @param	int		$id
	 * @return	array
	 */
	
	public function cat_get($id)
	{
		// required
			global $cosa, $db;
			if(!isset($id) || empty($id)) return false;
		
		// execute query
			$sql = "SELECT * FROM ".$db->module('news_cat')." WHERE id ='".addslashes($id)."' LIMIT 1";
			$res = @mysql_query($sql) or $cosa->oops('Could not fetch category.', 'db');
		
		// return result
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Get all news categories from a news item
	 * 
	 * @param	int		$news_id
	 * @param	bool	$returnString
	 * @return	array/string
	 */
	
	public function getCats($news_id=false, $returnString=false)
	{
		// required
			global $cosa, $db, $m;
			$catarr = array();
			$catstr = '';
		
		// execute query
			if($news_id) $sql = "SELECT c.* FROM ".$db->module('news_cat')." c, ".$db->module('news_rel')." r WHERE r.news_id ='".addslashes($news_id)."' AND c.id = r.cat_id ORDER BY c.title";
			else $sql = "SELECT * FROM ".$db->module('news_cat')." ORDER BY title";
			$res = @mysql_query($sql) or $cosa->oops('Could not fetch categories.', 'db');
		
		// get items
			while($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
				$catarr[] = $row;
				if($catstr != '') $catstr .= ', ';
				$catstr .= '<a href="'.$cosa->system('base-url').'/?m='.$m.'&s=cat&edit='.$row['id'].'">'.stripslashes($row['title'])."</a>";
			}
		
		// return string
			return ($returnString) ? $catstr : $catarr;
		
	}
	
	
	/**
	 * Get the default category
	 * 
	 * @return	array
	 */
	
	public function getDefaultCat()
	{
		global $cosa, $db;
		$sql = "SELECT * FROM ".$db->module('news_cat')." WHERE `default`= '1'";
		$res = @mysql_query($sql) or $cosa->oops('Could not fetch default category.', 'db');
		$row = mysql_fetch_array($res);
		return ($row) ? $row : false;
	}
	
	
	/**
	 * Update the category relations
	 * 
	 * @param	int		$news_id
	 * @param	array	$postVars
	 * @return	bool
	 */
	
	private function _updateCategories($news_id, $postVars)
	{
		// required
			global $cosa, $db, $lang;
			$addedOne = false;
		
		// delete all current relations
			$sql = "DELETE FROM ".$db->module('news_rel')." WHERE news_id ='".addslashes($news_id)."'";
			@mysql_query($sql) or $cosa->kill($lang->get('rel-news-failed'), 'db');
		
		// insert new relations
			$cats = $this->getCats();
			foreach($cats as $k => $cat) {
				if(isset($postVars['cat_'.$cat['id']]) && $postVars['cat_'.$cat['id']] == '1') {
					$addedOne = true;
					$sql = "INSERT INTO ".$db->module('news_rel')." SET news_id='".addslashes($news_id)."', cat_id='".addslashes($cat['id'])."'";
					@mysql_query($sql) or $cosa->kill($lang->get('rel-news-failed'), 'db');
				}
			}
		
		// none added, add default
			if(!$addedOne) {
				$default = $this->getDefaultCat();
				$sql = "INSERT INTO ".$db->module('news_rel')." SET news_id='".addslashes($news_id)."', cat_id='".addslashes($default['id'])."'";
				@mysql_query($sql) or $cosa->kill($lang->get('rel-news-failed'), 'db');
			}
		
		// return success
			return true;
		
	}
	
	
}

?>